<template>
    <div class="chatHistory">
        <!-- 发送时间 -->
        <div class="chatTime">{{ props.chatHistory?.time ? ChatViewApi.formatTimestamp(props.chatHistory.time, true) : "" }}</div>
        <!-- 系统消息 -->
        <div v-if="props.chatHistory?.role === ChatRoleTypes.System" class="systemMessage chatBubbleBox">
            <div class="chatBubble" :class="getChatBubble()">
                <div class="bubble"></div>
                <div class="content" v-html="props.chatHistory?.content"></div>
            </div>
        </div>
        <!-- 普通消息 -->
        <div v-else class="message" :class="props.chatHistory?.role === ChatRoleTypes.Self ? 'chatOneself' : 'chatOthers'">
            <!-- 用户头像（对方） -->
            <div class="userAvatar" v-if="props.chatHistory?.role === ChatRoleTypes.Others">
                <img :src="getUserAvatar()" />
            </div>
            <!-- 消息 内容 -->
            <div class="messageContent" :class="props.chatHistory?.userName && props.chatHistory?.userName.length > 0 ? '' : 'nullUserName'">
                <div class="userNameBox" v-if="props.chatHistory?.userName && props.chatHistory?.userName.length > 0">
                    <!-- 用户标签（对方） -->
                    <div class="userLabel" v-if="props.chatHistory?.permission && props.chatHistory?.permission !== Permission.None && props.chatHistory?.role === ChatRoleTypes.Self"
                    :class="props.chatHistory?.permission === Permission.Teachers ? 'teachers'
                    : props.chatHistory?.permission === Permission.Administrators ? 'administrators'
                    : props.chatHistory?.permission === Permission.Tourists ? 'tourists' 
                    : props.chatHistory?.permission === Permission.Exit ? 'exit' : ''">
                        {{ getUserLabel() }}
                    </div>
                    <!-- 用户名称 -->
                    <span class="userName">
                        {{ props.chatHistory?.userName }}
                    </span>
                    <!-- 用户标签（自己） -->
                    <div class="userLabel" v-if="props.chatHistory?.permission && props.chatHistory?.permission !== Permission.None && props.chatHistory?.role === ChatRoleTypes.Others":class="props.chatHistory?.permission === Permission.Teachers ? 'teachers'
                    : props.chatHistory?.permission === Permission.Administrators ? 'administrators'
                    : props.chatHistory?.permission === Permission.Tourists ? 'tourists' 
                    : props.chatHistory?.permission === Permission.Exit ? 'exit' : ''">
                        {{ getUserLabel() }}
                    </div>
                </div>
                <div class="chatBubbleBox">
                    <div class="chatBubble" :class="getChatBubble()">
                        <div class="bubble"></div>
                        <div class="content">
                            <div class="contentText" v-if="chatHistoryContent.length > 0" v-html="chatHistoryContent"></div>
                            <div class="contentText think" v-if="chatHistoryRenderedThink.length > 0" v-html="chatHistoryRenderedThink"></div>
                            <div class="contentText" v-if="chatHistoryRenderedMarkdown.length > 0">
                                <v-md-preview  :text="chatHistoryRenderedMarkdown" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 用户头像（自己） -->
            <div class="userAvatar" v-if="props.chatHistory?.role === ChatRoleTypes.Self">
                <img :src="selfAvatar" />
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue';
import { userAvatar } from  '@/types/Base64Image';
import { ChatViewApi } from '@/components/message/ChatList.vue';
import { chatBubbleApi, ChatRoleTypes } from '@/assets/chatBubble/chatBubble';
import { userApi } from '@/api/Users';
import MarkdownIt from 'markdown-it';
import { OllamaApi } from '@/api/Ollama';

export default defineComponent({
    name: 'chatHistory',
});

// 权限
export const Permission = {
    Teachers: 'Teachers', // 老师
    Administrators: 'Administrators', // 管理员
    Tourists: 'Tourists', // 游客
    None: 'None', // 无权限
    Exit: 'Exit', // 已退出
} as const;

// 聊天记录
export interface ChatHistoryData {
    chatTitle?: string; // 聊天标题
    role: keyof typeof ChatRoleTypes;   // 角色
    userName?: string;  // 用户名
    permission?: keyof typeof Permission; // 权限
    userId?: string;    // 用户ID
    content: string;    // 内容
    bubbleName?: string; // 气泡名称
    time?: number;      // 发送时间
}
</script>
<script setup lang="ts">
    const chatHistoryRenderedThink = ref<string>('');
    const chatHistoryRenderedMarkdown = ref<string>('');
    const chatHistoryContent = ref<string>('');
    const selfAvatar = ref<string>('');
    const md = new MarkdownIt();

    const props = withDefaults(defineProps<{
        chatHistory?: ChatHistoryData;
    }>(), {
        chatHistory: () => {
            return {
                role: ChatRoleTypes.Others,
                permission: Permission.None,
                avatar: '',
                content: '',
                time: 0,
            };
        }
    });

    // 获取用户标签
    const getUserLabel = () => {
        switch (props.chatHistory.permission) {
            case Permission.Exit:
                return "已退出";
            case Permission.Tourists:
                return "游客";
            case Permission.Teachers:
                return "老师";
            case Permission.Administrators:
                return "管理员";
            default:
                return "游客"; // 默认返回游客
        }
    };

    // 获取聊天气泡
    const getChatBubble = () => {
        if (props.chatHistory.bubbleName) return chatBubbleApi.getName(props.chatHistory.role, props.chatHistory.bubbleName);
        return  chatBubbleApi.getName(props.chatHistory.role, 'default');
    }

    // 获取用户头像
    const getUserAvatar = (): string => {
        if (props.chatHistory?.userId && props.chatHistory?.userId.length > 0)
        {
            if (props.chatHistory?.userId == 'assistant') return OllamaApi.getAvatar();
            return props.chatHistory?.userId + '/avatar.png';
        }
        return userAvatar();
    }

    // 获取记录内容
    const getContent = () => {
        if (!props.chatHistory?.content)
        {
            chatHistoryRenderedThink.value = '';
            chatHistoryRenderedMarkdown.value = '';
            chatHistoryContent.value = '';
            return;
        }
        
        // 如果不是助手，则直接返回内容
        if (props.chatHistory?.userId && props.chatHistory?.userId.length > 0)
        {
            if (props.chatHistory?.userId != 'assistant')
            {
                chatHistoryRenderedThink.value = '';
                chatHistoryRenderedMarkdown.value = '';
                chatHistoryContent.value = md.render(props.chatHistory?.content);
                return;
            }
        }
        else
        {
            chatHistoryRenderedThink.value = '';
            chatHistoryRenderedMarkdown.value = '';
            chatHistoryContent.value = md.render(props.chatHistory?.content);
            return;
        }

        const content = props.chatHistory?.content;

        const thinkMatch = content.match(/<think>([\s\S]*?)(?:<\/think>|$)/);
        const thinkContent = thinkMatch?.[1] || '';
        const remainingContent = content.replace(/<think>[\s\S]*?(?:<\/think>|$)/, '');

        // 分别渲染
        const renderedThink = md.render(thinkContent);  // 单独解析 think 内容
        const renderedMarkdown = md.render(remainingContent); // 渲染其余部分
        
        // 赋值
        chatHistoryRenderedThink.value = renderedThink;
        chatHistoryRenderedMarkdown.value = renderedMarkdown;
        chatHistoryContent.value = '';
    }
    
    // 监听 props.chatHistory?.content 的变化
    watch(() => props.chatHistory?.content, async (newValue, oldValue) => {
        if (newValue !== oldValue) {
            getContent();
        }
        selfAvatar.value = (await userApi.getLoginUserData()).avatarPath
    }, { immediate: true, deep: true } // 初始化时立即执行一次 , 深度监听数组变化
    );

</script>

<!-- 聊天气泡样式 -->
<style src="@/assets/chatBubble/chatBubble.css" scoped></style>
<style scoped>
.chatHistory {
    width: 100%;
    padding: 10px 0px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
}

/* 发送时间 */
.chatHistory .chatTime {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 12px;
    padding-bottom: 5px;
    color: rgba(100, 100, 100, 1);
}

/* 系统消息 */
.chatHistory .systemMessage {
    max-width: 80%;
    font-size: 14px;
    display: flex;
    justify-content: center;
}

/* 普通消息 */
.chatHistory .message {
    width: 100%;
    display: flex;
    font-size: 14px;
    padding: 0px 15px;
    margin-bottom: 20px;
    align-items: flex-start;
}

.chatHistory .message.chatOneself, /* 消息自己 */
.chatHistory .message.chatOneself .messageContent .userNameBox,  /* 名称 */
.chatHistory .message.chatOneself .messageContent .chatBubbleBox /* 聊天气泡对齐方式 */
{
    justify-content: flex-end;
}
.chatHistory .message.chatOthers,
.chatHistory .message.chatOthers .messageContent .userNameBox,
.chatHistory .message.chatOthers .messageContent .chatBubbleBox {
    justify-content: flex-start;
}

/* 消息头像 */
.chatHistory .message .userAvatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-top: 5px;
    overflow: hidden;
    border: 2px solid rgba(0, 185, 255, 1);
}
.chatHistory .message .userAvatar img {
    width: 100%;
    height: 100%;
}

/* 消息内容框 */
.chatHistory .messageContent {
    padding: 0px 10px;
    width: 60%;
}
.chatHistory .messageContent.nullUserName {
    padding-top: 5px;
}

/* 用户名称 */
.chatHistory .messageContent .userNameBox {
    width: 100%;
    height: 25px;
    display: flex;
    align-items: center;
    overflow: hidden;
}
.chatHistory .messageContent .userNameBox .userName {
    max-width: calc(100% - 100px);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
/* 用户标签 */
.chatHistory .messageContent .userLabel {
    max-width: 100px;
    padding: 2px 5px;
    font-size: 10px;
    border-radius: 5px;
    margin: 0px 5px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
/* 标签：老师 */
.chatHistory .messageContent .userLabel.teachers {
    background-color: rgba(250, 221, 213, 1);
    color: rgba(255, 141, 64, 1);
}
/* 标签：管理员 */
.chatHistory .messageContent .userLabel.administrators {
    background-color: rgba(198, 225, 255, 1);
    color: rgba(0, 185, 255, 1);
}
/* 标签：游客 */
.chatHistory .messageContent .userLabel.tourists {
    background-color: rgba(213, 250, 221, 1);
    color: rgba(64, 185, 141, 1);
}
/* 标签：退出 */
.chatHistory .messageContent .userLabel.exit {
    background-color: rgba(223, 223, 236, 1);
    color: rgba(158, 158, 158, 1);
}
</style>
